package util

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"

	"mumu_stock_trad/model"

	_ "github.com/go-sql-driver/mysql" // MySQL driver
)

// ApiResponse represents the structure of the API response
type ApiResponse struct {
	ShowapiResCode  int    `json:"showapi_res_code"`
	ShowapiResError string `json:"showapi_res_error"`
	ShowapiResID    string `json:"showapi_res_id"`
	ShowapiResBody  struct {
		RetCode int                    `json:"ret_code"`
		List    []StockDataApiResponse `json:"list"`
	} `json:"showapi_res_body"`
}

// StockDataApiResponse represents the structure of stock data inside the API response
type StockDataApiResponse struct {
	StockName  string `json:"stockName"`
	TradeMoney string `json:"trade_money"`
	DiffMoney  string `json:"diff_money"`
	OpenPrice  string `json:"open_price"`
	Code       string `json:"code"`
	Date       string `json:"date"`
	MinPrice   string `json:"min_price"`
	Market     string `json:"market"`
	TradeNum   string `json:"trade_num"`
	ClosePrice string `json:"close_price"`
	MaxPrice   string `json:"max_price"`
	Swing      string `json:"swing"`
	DiffRate   string `json:"diff_rate"`
	Turnover   string `json:"turnover"`
}

func FetchStockListSApi(code string, name string, begin string, end string) ([]model.StockDataShowApi, interface{}, error) {
	// ShowAPI endpoint and key
	url := "https://route.showapi.com/131-47"
	appKey := "c9A84EFCb2C34EEdaAACa3Dd3C1D7728"

	// Prepare POST data
	data := strings.NewReader(fmt.Sprintf("begin=%s&end=%s&code=%s", begin, end, code))

	// Create a new HTTP POST request
	req, err := http.NewRequest("POST", url, data)
	if err != nil {
		log.Fatalf("Failed to create HTTP request: %v", err)
	}

	// Set headers
	req.Header.Set("appKey", appKey)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// Send HTTP request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("HTTP POST request failed: %v", err)
	}
	defer resp.Body.Close()

	// Check HTTP status
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP request failed with status code: %d", resp.StatusCode)
	}

	var response ApiResponse

	err = json.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		log.Fatalf("Failed to decode JSON response: %v", err)
	}

	// Check ShowAPI response code
	if response.ShowapiResCode != 0 {
		log.Fatalf("ShowAPI request failed: %s", response.ShowapiResError)
	}

	list := []model.StockDataShowApi{}

	for _, da := range response.ShowapiResBody.List {
		stock := model.StockDataShowApi{
			StockName:  name,
			TradeMoney: parseFloat(da.TradeMoney),
			DiffMoney:  parseFloat(da.DiffMoney),
			OpenPrice:  parseFloat(da.OpenPrice),
			StockCode:  da.Code,
			Date:       da.Date,
			MinPrice:   parseFloat(da.MinPrice),
			Market:     da.Market,
			TradeNum:   parseInt(da.TradeNum),
			ClosePrice: parseFloat(da.ClosePrice),
			MaxPrice:   parseFloat(da.MaxPrice),
			Swing:      parseFloat(da.Swing),
			DiffRate:   parseFloat(da.DiffRate),
			Turnover:   parseFloat(da.Turnover),
		}
		list = append(list, stock)
	}

	// fmt.Println("Stocks data saved successfully!")

	return list, response, nil
}
